package com.leyou.upload.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.enums.ExceptionEnum;
import com.leyou.exception.LyException;
import com.leyou.upload.properties.OSSProperties;
import com.leyou.upload.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/4/29 0029
 * Time: 10:59
 */
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg", "image/bmp");
    @Autowired
    private OSS client;
    @Autowired
    private OSSProperties prop;

    @Override
    public String upLoadImg(MultipartFile file) {
        //获取文件类型
        String fileContentType = file.getContentType();
        //校验文件类型
        if (!suffixes.contains(fileContentType)) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        // 2)校验图片内容
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        if (image == null) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //生成保存图片的目录 ，保存到nginx所在目录的HTML下，即可实现通过NGINX访问
        File dir = new File("D:\\Program Files\\nginx-1.12.2\\html");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //保存图片
        try {
            file.transferTo(new File(dir, file.getOriginalFilename()));
            return "http://image.leyou.com/" + file.getOriginalFilename();
        } catch (IOException e) {
            log.error("保存失败！");
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
    }

    @Override
    public Map<String, Object> getAliSignature() {
        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);
            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
